package cn.bingo.yunsj.mail;

import cn.bingo.yunsj.common.exception.EmException;
import cn.bingo.yunsj.common.exception.OwnException;
import cn.bingo.yunsj.mail.model.FileProperties;
import cn.bingo.yunsj.mail.model.NewMailModel;
import cn.bingo.yunsj.mail.model.ImageModel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.MessagingException;
import java.io.*;
import java.util.List;

/**
 * 解析html，变成字符串
 */
public class HtmlParse {

    private BufferedReader br = null;

    private StringBuffer sb = null;

    private static final Logger logger = LoggerFactory.getLogger(HtmlParse.class);

    public void doHtmlParse(NewMailModel newMailModel, List<ImageModel> imageModels) throws IOException {

        String html = "";

        // 分为两种，doc解析成得html与docx解析成得html
        if (newMailModel.getWordPath().endsWith("docx")) { // 2007 及以后
            html = htmlParseToDocx(newMailModel.getHtmlPath(), imageModels);
        } else { // 2003 之前
            html = htmlParseToDoc(newMailModel.getHtmlPath(), imageModels);
        }

        logger.info("html字符串：" + html);

        FileProperties.setHtml(html);

        // 进入真正得邮件发送了
        MailSend mailSend = new MailSend();
        try {
            mailSend.doSend(newMailModel, imageModels, html);
        } catch (MessagingException e) {
            throw new OwnException(EmException.FILE_EXCPTION, e.getMessage());
        }
    }

    private String htmlParseToDoc(String htmlPath, List<ImageModel> imageModels) throws IOException {
        //读取html文件
        br = new BufferedReader(
                new InputStreamReader(
                        new FileInputStream(htmlPath), "utf-8"));
        String s = null;
        sb = new StringBuffer();
        int i = 0;
        int index = 0;
        String imageName = "";
        while ((s = br.readLine()) != null) {
            //当读到最后一个body时
            if (s.contains("body") && i == 1) {
                break;
            }
            if (s.contains("body") && i == 0) {
                i = 1;
            }
            if (i == 1 && !s.contains("body")) {
                //这里还需要处理图片
                if (s.contains("src")) {
                    //to do,jpg替换
                    imageName = imageModels.get(index).getImageName();
                    sb.append(s.substring(0, s.indexOf("src") + 4) + "'cid:" + imageName + "'");
                    sb.append(s.substring(s.indexOf(imageName.substring(0, imageName.indexOf("."))) + imageName.length() + 1, s.length()));
                    index++;
                } else {
                    //模板替换，参照readme里面得模板替换规则,待完成
                    if (s.contains("${userName}")) {
                        sb.append(s.replace("${userName}", "zmx"));
                    } else {
                        sb.append(s);
                    }
                }
            }
        }
        return sb.toString();
    }

    private String htmlParseToDocx(String htmlPath, List<ImageModel> imageModels) throws IOException {

        br = new BufferedReader(
                new InputStreamReader(
                        new FileInputStream(htmlPath), "utf-8"));
        // 用来记录每次更新后得字符串
        sb = new StringBuffer();
        // html字符串
        String html = br.readLine();
        // 用来记录到第几个字符了
        int index = 0;
        // 用来存放上一次处理得图片全称
        String pre_Name = "";
        // 当前处理得图片全称
        String imageName = "";
        // 只留下body内得html字符
        String s_body = html.substring(html.indexOf("<body>") + 6, html.indexOf("</body>") - 6);

        //循环替换图片，因为通过poi解析docx得文档，会产生"word/media"
        while (s_body.contains("word/media")) {
            sb = new StringBuffer();
            imageName = imageModels.get(index).getImageName();
            String imageEnd = imageName.substring(imageName.indexOf(".") + 1, imageName.length());  //jpg
            sb.append(s_body.substring(0, s_body.indexOf("src", getIndex(s_body, index, "src")) + 4) + "'cid:" + imageName + "'");

            // 比较图片是否更换了，需要重置下index
            if (StringUtils.equals(imageName, pre_Name)) {
                pre_Name = imageName;
            } else {
                index = 0;
                pre_Name = imageName;
            }
            sb.append(s_body.substring(s_body.indexOf(imageEnd, getIndex(s_body, index, imageEnd)) + imageName.length() + 1, s_body.length()));
            index++;
            s_body = sb.toString();
        }
        return sb.toString();
    }

    //递归读取
    private static int getIndex(String path, int j, String s) {
        if (j == 0) {
            return 0;
        }
        if (j == 1) {
            return path.indexOf(s) + 1;
        } else {
            return path.indexOf(s, getIndex(path, --j, s)) + 1;
        }
    }

    // 文件流销毁
    private void destory() {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                throw new OwnException(EmException.FILE_EXCPTION, "关闭失败");
            }
        }
    }
}
